// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Linq;

namespace SnapObjects.Data
{
    internal class PocoStatefulModel<TModel> : StatefulModel<TModel>, IUpdateSplitable
    {
        public PocoStatefulModel(
            ICompositeModelAccessor<TModel> compositeModelAccessor,
            TModel model,
            ModelState modelState,
            ChangeTrackingStrategy changeTrackingStrategy)
            : base(compositeModelAccessor, model, modelState, changeTrackingStrategy)
        {
        }

        public PocoStatefulModel(
            ICompositeModelAccessor<TModel> compositeModelAccessor,
            TModel originalModel,
            TModel currentModel,
            ChangeTrackingStrategy changeTrackingStrategy)
            : base(compositeModelAccessor, originalModel, currentModel, changeTrackingStrategy)
        {
        }

        public PocoStatefulModel(
            IModelFactory<TModel> modelFactory,
            TModel model,
            ModelState modelState,
            ChangeTrackingStrategy changeTrackingStrategy)
            : base(modelFactory, model, modelState, changeTrackingStrategy)
        {
        }

        // Used for entry track
        protected PocoStatefulModel(
            ICompositeModelAccessor<TModel> compositeModelAccessor,
            IModelFactory<TModel> modelFactory,
            ModelState modelState,
            ChangeTrackingStrategy changeTrackingStrategy)
            : base(compositeModelAccessor, modelFactory, modelState, changeTrackingStrategy)
        {
        }

        public IStatefulModel SplitDeletedFromUpdate(ChangeTrackingStrategy changeTrackingStrategy)
        {
            return this.CreateInstance(_originalModel, ModelState.Deleted, changeTrackingStrategy);
        }

        public IStatefulModel SplitInsertedFromUpdate(ChangeTrackingStrategy changeTrackingStrategy)
        {
            return this.CreateInstance(_currentModel, ModelState.NewModified, changeTrackingStrategy);
        }

        public IStatefulModel CreateInstance(
            TModel model,
            ModelState modelState,
            ChangeTrackingStrategy changeTrackingStrategy)
        {
            if (this.ModelState == ModelState.Modified)
            {
                return new PocoStatefulModel<TModel>(_modelFactory, model, modelState, changeTrackingStrategy);
            }

            throw new InvalidOperationException(Properties.Resource.DELTHENINS_MODELSTATE_INVALID);
        }
    }
}
